<?php
/*
 *
 */
class dbapiController extends coreController{

    /*
    function __construct(){

    }
    */


    /*
     * Удалить аяксом картинку
     * entity - имя таблицы
     */
    function deleteAction(){

        $entity = $this->registry->request->postParam('entity') ;
        $id = $this->registry->request->postParam('id') ;
        $link = null;

        $responcestatus = 'ok';
        $mess = '';

        $unit = $this->registry->request->postParam('unit') ;

        if($entity == 'photo')
            $column = 'photo_id';
        $value = $id;

        #
        $model_name = ucfirst($entity) . "Model";
        $model = new $model_name($column, $value);
        $data = $model->getData();
        $model->del();


        unset($model);

        if(isset($data['link'])) $link = $data['link'];
        if(isset($data[0]['link'])) $link = $data[0]['link'];

        #
        if($entity == 'photo'){
            if(!is_null($link)){
                //TODO роутинг (сейчас есть только плитка )
                $file_name_1 = $link;
                $file_name_2 = "sm_" . $link;
                try {
                  $this->registry->Model->delRemoteFile($file_name_1,$unit);
                  $this->registry->Model->delRemoteFile($file_name_2,$unit);
                } catch(Exception $e){
                  $mess = $e->getMessage();
                  fb($mess);
                }
            }

        }

        #
        $json_responce = array(
            'responcestatus' => $responcestatus,
            'message' => $mess
        );

        $this->json($json_responce);
    }

    /*
     * Поменять аяксом визибельность картинки
     */
    function togglephotovisibilityAction(){
        $responcestatus = 'ok';
        $mess = '';

        $entity = $this->registry->request->postParam('entity') ;
        $id = $this->registry->request->postParam('id') ;
        $unit = $this->registry->request->postParam('unit') ;
        $is_active = 0;



        #
        $model = new PhotoModel($column = 'photo_id', $id);

        $data_exists = $model->getData();


        if(isset($data_exists[0])){
            if(isset($data_exists[0]['is_active'])){
                $is_active = (int)$data_exists[0]['is_active'];
                if($is_active === 1) $is_active = 0;
                else $is_active = 1;
            }
            $data = array(
                "is_active" => $is_active
            );
            $data = array_merge($data_exists[0],$data );
        }

        $data = array(0 => $data);

        $model->setData($data);

        $model->Flush();

        unset($model);

        #
        $json_responce = array(
            'responcestatus' => $responcestatus,
            'message' => $mess
        );

        $this->json($json_responce);
    }

}